package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * 客户端代理类
 * 1、封装request请求对象
 * 2、创建RpcClient
 * 3、发送消息
 * 4、返回结果
 */

@Component
public class RpcClientProxy {

    @Autowired
    private RpcClient rpcClient;

    public  Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1、封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        System.out.println("========");
                        //2、创建RpcClient对象
//                        RpcClient rpcClient = new RpcClient("127.0.0.1", 8899);
                        try {
                            System.out.println("11111");
                            //3、发送消息
                            Object object = rpcClient.send(JSON.toJSONString(rpcRequest));
                            System.out.println("+++++++++");
                            RpcResponse response = JSON.parseObject(object.toString(), RpcResponse.class);
                            System.out.println("---------");
                            if (response.getError() != null) {
                                throw new RuntimeException(response.getError());
                            }

                            Object result = response.getResult();
//                            if(result==null){
//                                return JSON.toJSONString("{}");
//                            }
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw e;
                        }
// finally {
//                            rpcClient.close();
//                        }
                    }
                });
    }
}
